<?php

function observation_validation_page() {
  $func_args = func_get_args();
  $confirm = 0;
  if (count($func_args) > 0) {
    if ($func_args[0] == 'confirm') {
      $confirm = 1;
    }
  }
  $html = '';
  if (is_user_validator()) {
    global $user;
    $validator_expertise = get_user_validation_expertise($user->uid , TRUE);
    if ($user->uid == 1) {
      $confirm = 1;
    }
    if ($confirm == 1) {
      $path = drupal_get_path('module','win_observation');
      drupal_add_js($path . '/js/external/jquery-1.3.2.js');
      drupal_add_js($path . '/js/external/jquery.dataTables.js');
      drupal_add_js($path . '/js/search_results_page.js');

      drupal_add_css($path . '/css/jquery.datatable/css/demo_table.css');

      $html .= show_records_for_validation($validator_expertise);
    }
    else {
      $html .= show_user_validation_expertise($validator_expertise);
      $base_path = base_path();
      $html .= <<<EOT
      <div style="text-align: center; padding: 5px; background-color: #FFFFFF">
        <div>
          The purpose of validation is to varify the authenticity, accurracy, correctness of the biodiversity observations contributed by the citizens and naturalist across the globe. Please proceed to validate these records, if you truly beleive that you have expertise to do so.

          If not, please click <a href="{$base_path}">here</a>.
        </div>
        <div><a href="{$base_path}observation/validate/confirm">Proceed</a></div>
      </div>
EOT;
    }
  }
  else {
    //observation_validator_form();
    $base_path = base_path();
    $html = <<<EOT
    <div class="messages error">
      You are not a validator currently. Please click <a href="{$base_path}observation/validator_request">here</a> to file a request to be a validator.
    </div>
EOT;
  }
  return $html;
}

function get_user_validation_expertise($uid, $ret_arr = FALSE) {
  $result = db_query('select expertise_type, expertise_mapping from win_validator_expertise where uid = %d', array($uid));
  if (!$result) {
    if ($ret_arr) {
      return FALSE;
    }
    else {
      die(json_encode(set_error_arr("Error talking to DB. Please try after sometime.")));
    }
  }
  else {
    $data = array();

    while ($obj = db_fetch_object($result)) {
      $data[$obj->expertise_type][] = $obj->expertise_mapping;
    }

    if ($ret_arr) {
      return $data;
    }
    else {
      $arr = set_no_error_arr("");
      $arr['data'] = $data;
      die(json_encode($arr));
    }
  }
}

function get_info_html($info) {
  return '<div style="border: 1px solid rgb(217, 234, 245); padding: 2px; margin: 2px;">'.$info.'</div>';
}

function show_user_validation_expertise($validator_expertise) {
  $languages = array();
  if (isset($validator_expertise['language'])) {
    $languages = $validator_expertise['language'];
  }
  $taxanomies = array();
  if (isset($validator_expertise['taxanomy'])) {
    $taxanomies = $validator_expertise['taxanomy'];
  }
  $ecosystems = array();
  if (isset($validator_expertise['ecosystem'])) {
    $ecosystems = $validator_expertise['ecosystem'];
  }
  $waterbodies = array();
  if (isset($validator_expertise['waterbody'])) {
    $waterbodies = $validator_expertise['waterbody'];
  }
  $locations = array();
  if (isset($validator_expertise['location'])) {
    $locations = $validator_expertise['location'];
  }
  $base_path = base_path();
  $html = <<<EOT
    <div><b>Your current expertise are: </b></div>
    <div id="divValidationRequest" style="font-size: 10px;">
EOT;
  if (count($languages) > 0) {
    $html .= <<<EOT
      <fieldset id="fsLanguages">
        <legend>Languages</legend>
        <div id="divLanguages">
EOT;
    foreach ($languages as $lang_info) {
      $html .= get_info_html($lang_info);
    }
    $html .= <<<EOT
        </div>
      </fieldset>
EOT;
  }
  if (count($taxanomies) > 0) {
    $html .= <<<EOT
      <fieldset id="fsSciTerms">
        <legend>Taxanomy</legend>
        <div id="divTaxanomies">
EOT;
    foreach ($taxanomies as $taxa_info) {
      $html .= get_info_html($taxa_info);
    }
    $html .= <<<EOT
        </div>
      </fieldset>
EOT;
  }
  if (count($ecosystems) > 0) {
    $html .= <<<EOT
      <fieldset id="fsEcosystems">
        <legend>Ecosystems</legend>
        <div id="divEcosystems">
EOT;
    foreach ($ecosystems as $eco_info) {
      $html .= get_info_html($eco_info);
    }
    $html .= <<<EOT
        </div>
      </fieldset>
EOT;
  }
  if (count($waterbodies) > 0) {
    $html .= <<<EOT
      <fieldset id="fsWaterbodies">
        <legend>Waterbodies</legend>
        <div id="divWaterbodies">
EOT;
    foreach ($waterbodies as $waterbody_info) {
      $html .= get_info_html($waterbody_info);
    }
    $html .= <<<EOT
        </div>
      </fieldset>
EOT;
  }
  if (count($locations) > 0) {
    $html .= <<<EOT
      <fieldset id="fsLocations">
        <legend>Locations</legend>
        <div id="divLocations">
EOT;
    foreach ($locations as $loc_info) {
      $html .= get_info_html($loc_info);
    }
    $html .= <<<EOT
        </div>
      </fieldset>
EOT;
  }
  $html .= <<<EOT
    </div>
    <div style="text-align: center; padding: 5px; background-color: rgb(255, 255, 255); margin-top: 10px; margin-bottom: 10px;">
      <a href="{$base_path}observation/validator_request">Change expertise</a>
    </div>
EOT;

  return $html;
}

function show_records_for_validation($validator_expertise) {
  $observations = get_unvalidated_observations_for_criteria($validator_expertise);
  return show_search_results($observations, TRUE);
  //return win_observation_display_unvalidated_records($observations);
}

function get_unvalidated_observations_for_criteria($val_criteria) {
  global $user;
  $uid = $user->uid;

  $where = array();

  if (isset($val_criteria['location'])) {
    $where = array_merge($where, get_location_criteria($val_criteria['location']));
  }

  if (isset($val_criteria['waterbody'])) {
    $where = array_merge($where, get_waterbody_criteria($val_criteria['waterbody']));
  }

  if (isset($val_criteria['taxanomy'])) {
    $where = array_merge($where, get_taxanomy_criteria($val_criteria['taxanomy']));
  }

  if (isset($val_criteria['language'])) {
    $arr = array_merge($where, get_language_criteria($val_criteria['language']));
    $where = array_merge($where, $arr['where']);
    $cn_where = $arr['cn_where'];
  }

  if (isset($val_criteria['ecosystem'])) {
    $where = array_merge($where, get_ecosystem_criteria($val_criteria['ecosystem']));
  }

  $oids = get_oids_for_observation_table_criteria($where);
  $oids = array_merge($oids, get_oids_for_common_name_criteria($cn_where));

  $oids = array_unique($oids);

  $observations = get_observation_info_for_search_results($oids);

  return $observations;
}

function get_location_criteria($locations) {
  $where = array();

  $len = count($locations);
  if ($len == 1 && $locations[0] == 'World') { // Since all are to be returned just ignore
  }
  else {
    $crt = array();
    for ($i = 0; $i < $len; $i++) {
      $loc = strtolower($locations[$i]);
      $loc_arr = explode(' > ', $loc);
      $c = array();
      if (isset($loc_arr[0])) {
        $c[] = "lower(country) = '" . $loc_arr[0] . "'";
      }
      if (isset($loc_arr[1])) {
        $c[] = "lower(region) = '" . $loc_arr[1] . "'";
      }
      if (isset($loc_arr[2])) {
        $c[] = "lower(city) = '" . $loc_arr[2] . "'";
      }
      $crt[] = '(' . implode(' AND ', $c) . ')';
    }
    $where[] = '(' . implode(' OR ', $crt) . ')';
  }

  return $where;
}

function get_waterbody_criteria($waterbodies) {
  $where = array();

  $len = count($waterbodies);
  if ($len == 1 && strtolower($waterbodies[0]) == 'none') {
    $crt = array();
    $crt[] = "(waterbody_type is null or waterbody_type = '')";
    $crt[] = "(waterbody_name is null or waterbody_name = '')";
    $where[] = '(' . implode(' AND ', $crt) . ')';
  }
  else if ($len == 1 && strtolower($waterbodies[0]) == 'all') {
  }
  else {
    $crt = array();
    for ($i = 0; $i < $len; $i++) {
      $wb = strtolower($waterbodies[$i]);
      $c = array();
      $wb_arr = explode(':', $wb);
      $w_type = strtolower($wb_arr[0]);
      $w_name = strtolower($wb_arr[1]);
      $c[] = "lower(waterbody_type) = '{$w_type}'";
      if ($w_name != 'all') {
        $c[] = "lower(waterbody_name) = '{$w_name}'";
      }
      $crt[] = '(' . implode(' AND ', $c) . ')';
    }
    $where[] = '(' . implode(' OR ', $crt) . ')';
  }

  return $where;
}

function get_taxanomy_criteria($taxanomies) {
  $where = array();

  $len = count($taxanomies);
  if ($len == 1 && $taxanomies[0] == 'All') { // Since all are to be returned just ignore
  }
  else {
    $crt = array();
    for ($i = 0; $i < $len; $i++) {
      $taxa = strtolower($taxanomies[$i]);
      $taxa_arr = explode(' > ', $taxa);
      $c = array();
      $j = 0;
      if (isset($taxa_arr[$j])) {
        $c[] = "lower(s_kingdom) = '" . $taxa_arr[$j] . "'";
      }
      $j++;
      if (isset($taxa_arr[$j])) {
        $c[] = "lower(s_phylum) = '" . $taxa_arr[$j] . "'";
      }
      $j++;
      if (isset($taxa_arr[$j])) {
        $c[] = "lower(s_class) = '" . $taxa_arr[$j] . "'";
      }
      $j++;
      if (isset($taxa_arr[$j])) {
        $c[] = "lower(s_order) = '" . $taxa_arr[$j] . "'";
      }
      $j++;
      if (isset($taxa_arr[$j])) {
        $c[] = "lower(s_family) = '" . $taxa_arr[$j] . "'";
      }
      $j++;
      if (isset($taxa_arr[$j])) {
        $c[] = "lower(s_genus) = '" . $taxa_arr[$j] . "'";
      }
      $j++;
      if (isset($taxa_arr[$j])) {
        $c[] = "lower(s_species) = '" . $taxa_arr[$j] . "'";
      }
      $crt[] = '(' . implode(' AND ', $c) . ')';
    }
    $where[] = '(' . implode(' OR ', $crt) . ')';
  }

  return $where;
}

function get_language_criteria($languages) {
  $cn_where = array();
  $where = array();

  $len = count($languages);
  $crt = array();
  $c = array();
  for ($i = 0; $i < $len; $i++) {
    $lang = strtolower($languages[$i]);
    $crt[] = "lower(record_language) = '{$lang}'";
    $c[] = "lower(cn_language) = '{$lang}'";
  }
  $where[] = '(' . implode(' OR ', $crt) . ')';
  $cn_where[] = '(' . implode(' OR ', $c) . ')';

  return array('where' => $where, 'cn_where' => $cn_where);
}

function get_ecosystem_criteria($ecosystems) {
  $where = array();
  $len = count($ecosystems);
  if ($len == 1 && $ecosystems[0] == 'All') { // ignore
  }
  else {
    $crt = array();
    for ($i = 0; $i < $len; $i++) {
      $ecosystem = strtolower($ecosystems[$i]);
      $eco_arr = explode(' > ', $ecosystem);
      $c = array();
      if (count($eco_arr) == 1) { // all in parent specified
        $c[] = "ecosystem_id = (select id from win_ecosystems where ecosystem_type = '".$eco_arr[0]."') OR ecosystem_id in (select id from win_ecosystems where parent_id = (select id from win_ecosystems where ecosystem_type = '".$eco_arr[0]."'))";
      }
      else { // particular child ecosystem specified
        $c[] = "ecosystem_id = (select id from win_ecosystems where ecosystem_type = '".$eco_arr[1]."')";
      }
      $crt[] = '(' . implode(' AND ', $c) . ')';
    }
    $where[] = '(' . implode(' OR ', $crt) . ')';
  }

  return $where;
}

function get_oids_for_observation_table_criteria($where) {
  global $user;
  $uid = $user->uid;

  $oids = array();

  //$query = 'select id from win_observations where id not in (select distinct observation_id from win_validation where status = 1) and id not in (select id from win_observations where created_by = ' . $uid . ') ';
  // allow self validation
  $query = 'select id from win_observation_textual_data_with_ecosystem_view where id not in (select distinct observation_id from win_validation where status = 1) ';

  $FILTER_COND = ' OR '; // set it to AND if you want to filter rows.

  if (count($where) > 0) {
    $query .= ' AND (' . implode($FILTER_COND, $where) . ')';
  }

  $result = db_query($query);
  if (!$result) {
    return FALSE;
  }
  else {
    while ($obj = db_fetch_object($result)) {
      $oids[] = $obj->id;
    }
  }

  return $oids;
}

function get_oids_for_common_name_criteria($cn_where) {
  global $user;
  $uid = $user->uid;

  $oids = array();

  $query = 'select observation_id from win_common_names where observation_id not in (select distinct observation_id from win_validation where status = 1) and observation_id not in (select id from win_observations where created_by = ' . $uid . ')';
  if (count($cn_where) > 0) {
    $query .= ' AND ' . implode(' OR ', $cn_where);
  }
  $result = db_query($query);
  if (!$result) {
    return FALSE;
  }
  else {
    while ($obj = db_fetch_object($result)) {
      $oids[] = $obj->observation_id;
    }
  }

  return $oids;
}

function update_validation_request_status($params) {
  if (user_access('administer win_observation')) {
    $uid = $params['uid'];
    $status = $params['status'];
    $comments = utf8_encode($params['comments']);

    global $user;

    $query = "update win_validators set status = %d, comments = '%s', reviewed_by = %d, reviewed_on = now() where uid = %d";
    $query_args = array($status, $comments, $user->uid, $uid);
    $result = db_query($query, $query_args);
    if (!$result) {
      die(json_encode(set_error_arr("Error talking to DB. Please try after sometime.")));
    }
    else {
      die(json_encode(set_no_error_arr("Validation request status has been updated.")));
    }
  }
}